import Vue from 'vue'
import store from './store'
import App from './App'

const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	})
}
const json = type => {
	//模拟异步请求数据
	return new Promise(resolve => {
		setTimeout(() => {
			resolve(Json[type])
		}, 500)
	})
}

const prePage = () => {
	let pages = getCurrentPages()
	let prePage = pages[pages.length - 2]
	return prePage.$vm
}

Vue.config.productionTip = false
Vue.prototype.$fire = new Vue()
Vue.prototype.$store = store
Vue.prototype.$api = { msg, json, prePage }

//封装网络请求
Vue.prototype.sendRequest = function(param, backpage, backtype) {
	var _self = this,
		url = param.url,
		method = param.method,
		header = {},
		data = param.data || {},
		hideLoading = param.hideLoading || false

	//拼接完整请求地址
	var requestUrl = this.siteBaseUrl + url

	//请求方式:GET或POST(POST需配置header: {'content-type' : "application/x-www-form-urlencoded"},)
	if (method) {
		if (method.toUpperCase() === 'POST') {
			header['content-type'] = 'application/x-www-form-urlencoded'
		} else {
			header['content-type'] = 'application/x-www-form-urlencoded'
		}
	} else {
		method = 'GET'
		// header['content-type'] = 'application/json'
		header['content-type'] = 'application/x-www-form-urlencoded'
	}
	//用户交互:加载圈
	if (!hideLoading) {
		uni.showLoading({ title: '加载中...' })
	}
	console.log('网络请求start')
	//网络请求
	uni.request({
		url: requestUrl,
		method: method,
		header: header,
		data: data,
		success: res => {
			console.log('网络请求success:' + JSON.stringify(res))
			console.log(res.data)
			if (res.data.code) {
				if (res.data.code !== 200) {
					uni.showModal({ content: '' + res.data.msg })
					return
				}
			} else {
				uni.showModal({ content: '' + res.data.msg })
				return
			}
			typeof param.success === 'function' && param.success(res.data)
		},
		fail: e => {
			console.log('网络请求fail:' + JSON.stringify(e))
			uni.showModal({ content: '' + e.msg })
			typeof param.fail === 'function' && param.fail(e.data)
		},
		complete: () => {
			console.log('网络请求complete')
			if (!hideLoading) {
				uni.hideLoading()
			}
			typeof param.complete === 'function' && param.complete()
			return
		}
	})
}

Vue.prototype.siteHost = 'http://localhost:8080'
Vue.prototype.siteBaseUrl = Vue.prototype.siteHost + '/app/'
App.mpType = 'app'

const app = new Vue({ ...App })
app.$mount()
